<template>
  <div style="text-align: right; display: inline-block; margin: 0;">
    <el-button
      :loading="button.loading"
      :icon="button.icon"
      :size="button.size"
      :type="button.type"
      :width="button.width"
      @click="click"
      plain
      style="margin-right: 5px;"
      >{{ button.value }}
    </el-button>
  </div>
</template>

<script>
import _ from "lodash";
export default {
  name: "button_index",
  data: function() {
    return {
      button: {
        loading: false,
        size: "small ",
        value: "按钮",
        type: "",
        icon: "",
        width: "",
        time: 500,
        param: {},
        click: function() {}
      },
      btnType: [
        { value: "新增", type: "primary", icon: "el-icon-plus" },
        { value: "修改", type: "warning", icon: "el-icon-edit" },
        { value: "删除", type: "danger", icon: "el-icon-delete" },
        { value: "详情", type: "info", icon: "el-icon-date" },
        { value: "刷新", type: "success", icon: "el-icon-refresh-right" },
        { value: "上传", type: "primary", icon: "el-icon-upload2" }
      ]
    };
  },
  props: {
    btn: {},
    onclick: {
      type: Function,
      default: null
    },
    param: {},
    clickType: {
      type: Number,
      default: 0
    }
  },
  watch: {
    btn: {
      handler(newValue, oldValue) {
        this.btn = newValue;
      },
      deep: true
    }
  },
  methods: {
    buttonLoad: function() {
      this.button = _.cloneDeep(this.btn);
      const that = this;
      let type = "";
      let icon = "";
      //设置按钮样式
      try {
        this.btnType.forEach((item, index) => {
          if (item.value === that.button.value) {
            type = item.type;
            icon = item.icon;
            throw new Error("0");
          }
        });
      } catch (e) {
        if (e.message === "0") {
          that.button.type = type;
          that.button.icon = icon;
        }
      }
    },
    click() {
      this.button.loading = true;
      const _this = this;
      const timer = setTimeout(function() {
        _this.button.loading = false;
      }, this.button.time);
      if (this.clickType === 1) {
        this.button.click(this.param, this.button);
        if (this.onclick) {
          //    this.onclick(this.param);
        }
      } else if (this.clickType === 0) {
        this.button.click(this.button.param, this.button);
        //  this.onclick(this.param);
      }
      // 通过$once来监听定时器，在beforeDestroy钩子可以被清除。
      this.$once("hook:beforeDestroy", () => {
        clearInterval(timer);
      });
    }
  },
  mounted() {
    this.buttonLoad();
  }
};
</script>

<style scoped></style>
